package cn.cdzdjd.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import cn.cdzdjd.annotation.Login;
import cn.cdzdjd.entity.UserSession;
import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.UserSessionService;
import cn.cdzdjd.util.Result;
import cn.cdzdjd.util.TokenUtil;
import cn.cdzdjd.util.UserHolder;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;

/**
 * 权限(Token)验证
 *
 * @author
 */
@Component
@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {
	@Resource
	private UserSessionService userSessionService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Login annotation = null;
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
		}
		if (annotation == null) {
			return true;
		}

		// 从header中获取token
		String token = request.getHeader("Authorization");
		// token为空
		if (StrUtil.isBlank(token)) {
			throw new RenException(ErrorCode.NO_TOKEN);
			// return true;
		}
		// 从token中查询token信息
		try {
			String userId = TokenUtil.getUserId(token);
			UserSession user = userSessionService.findById(Long.valueOf(userId));
			// 如果查到用户
			if (user != null) {
				UserHolder.setHolder(user.getId());
				return true;
			} else {
				response.setHeader("expire", "1");
				Result<?> result = new Result<>().error(ErrorCode.PARSE_ERROR);
				response.setContentType("application/json;charset=utf-8");
				response.getWriter().write(new JSONObject(result).toString());
				return false;
			}
		} catch (Exception e) {
			if (e instanceof ExpiredJwtException) {
				Claims claims = ((ExpiredJwtException) e).getClaims();
				String userId = claims.get("userId").toString();
				UserSession user = userSessionService.findById(Long.valueOf(userId));
				// 如果查到用户
				if (user != null) {
					response.setHeader("token", TokenUtil.getToken(userId));
					return true;
				} else {
					response.setHeader("expire", "1");
					Result<?> result = new Result<>().error(ErrorCode.PARSE_ERROR);
					response.setContentType("application/json;charset=utf-8");
					response.getWriter().write(new JSONObject(result).toString());
					return false;
				}
			}else {
				e.printStackTrace();
			}
		}
		// 如果token过期暂不处理
//		try {
//			TokenUtil.expire(token);
//		} catch (ExpiredJwtException e) {
//
//			throw new RenException(ErrorCode.TOKEN_EXPIRE);
//		}
		return false;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		UserHolder.remove();
	}

}
